import threading
import keyboard
import pyautogui
import time 
import win32gui
import win32con
# 定义一个标志来表示是否处于模拟按键状态
is_simulating = False
# 定义一个锁对象
lock = threading.Lock()
# 禁用 PyAutoGUI 的 fail-safe 机制
pyautogui.FAILSAFE = False
key_value = ""
key_speed = 0.1
key_sync = True
# 模拟按键的函数
special_key_codes = {
    'enter': 13,
    'esc': 27,
    'tab': 9,
    'backspace': 8,
    'insert': 45,
    'delete': 46,
    'home': 36,
    'end': 35,
    'page up': 33,
    'page down': 34,
    'up': 38,
    'down': 40,
    'left': 37,
    'right': 39,
    'f1': 112,
    'f2': 113,
    'f3': 114,
    'f4': 115,
    'f5': 116,
    'f6': 117,
    'f7': 118,
    'f8': 119,
    'f9': 120,
    'f10': 121,
    'f11': 122,
    'f12': 123,
    'ctrl': 17,
    'shift': 16,
    'alt': 18
}

def send_key_to_all_windows( key , type):
    window_title = "魔兽世界"
    try:
        hwnd = win32gui.FindWindowEx(None, None, None, window_title)
        op = win32con.WM_KEYDOWN 
        if type != "down":
            op = win32con.WM_KEYUP
        if key in special_key_codes:
            key = chr(special_key_codes[key])
        if key == "space" : 
            key = ' '
        a_key = ord(key)
        print(a_key)
        while hwnd != 0:
            win32gui.PostMessage(hwnd, op, a_key, 0)  # 按下按键
            # win32gui.PostMessage(hwnd, win32con.WM_KEYUP, a_key, 0)  # 释放按键
            hwnd = win32gui.FindWindowEx(None, hwnd, None, window_title)
    except Exception as e:
        print("发生异常:", str(e))

# 监听键盘输入的回调函数
def on_key_event(event):
    global key_value, is_simulating, key_speed,key_sync
    key_code = event.name
    if event.event_type == "down":
        with lock:  #    加锁
            if keyboard.is_pressed('ctrl+alt') and event.name.isdigit():
                key_value = event.name
                is_simulating = True
            elif keyboard.is_pressed('ctrl+alt+`'):
                is_simulating = False 
            elif keyboard.is_pressed('ctrl+alt+n'):
                key_speed = 2.5
            elif keyboard.is_pressed('ctrl+alt+m'):
                key_speed = 0.1 
            else:
                if event.name == "home":
                    if key_sync : key_sync = False 
                    else : key_sync = True
                if key_sync:
                    print(event.name, event.event_type)
                    send_key_to_all_windows(key_code, event.event_type)
    elif event.event_type == "up":  
        if keyboard.is_pressed('ctrl+alt') and event.name.isdigit():
            key_value = event.name
            is_simulating = True
        elif keyboard.is_pressed('ctrl+alt+`'):
            is_simulating = False 
        elif keyboard.is_pressed('ctrl+alt+n'):
            key_speed = 2.5
        elif keyboard.is_pressed('ctrl+alt+m'):
            key_speed = 0.1  
        else:
            if key_sync:
                print(event.name, event.event_type)
                send_key_to_all_windows(key_code, event.event_type)
            
def simulate_key_press():
    global key_value, is_simulating, key_speed
    while True:
        try:
            with lock:  # 加锁
                if is_simulating:
                    # pyautogui.press(key_value)
                    send_key_to_all_windows(key_value,"down")
                    time.sleep(0.01)
                    send_key_to_all_windows(key_value,"up")
            time.sleep(key_speed)
        except pyautogui.FailSafeException:
            pass

# 启动模拟按键线程
threading.Thread(target=simulate_key_press, daemon=True).start()

# 监听键盘输入
keyboard.hook(on_key_event)

# 保持程序运行
keyboard.wait('end')